﻿using System;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
using Emico.Data.Repository;

namespace Emico.Data.Entity.Repository
{
    public abstract class DbUnitOfWork<C> : IDbUnitOfWork
        where C : DbContext
    {
        protected IDbContextWrapper Wrapper
        {
            get;
            private set;
        }

        public DbUnitOfWork(DbContext context)
            : this(new DbContextWrapper(context))
        {
        }
        public DbUnitOfWork(IDbContextWrapper wrapper)
        {
            if (wrapper == null)
                throw new ArgumentNullException("wrapper");
            
            this.Wrapper = wrapper;
        }

        #region IUnitOfWork

        public int Commit()
        {
            return this.Wrapper.SaveChanges();
        }

        public Task<int> CommitAsync()
        {
            return this.Wrapper.SaveChangesAsync();
        }

        public Task<int> CommitAsync(CancellationToken cancellationToken)
        {
            return this.Wrapper.SaveChangesAsync(cancellationToken);
        }

        public abstract T GetRepository<T>() where T : IRepository;

        #endregion

        #region Dispose

        private bool _disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    this.Wrapper.Dispose();
                }

                this._disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
